import { Config, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import * as request from 'request';
import * as _ from 'lodash';
import * as crypto from 'crypto';

/**
 * http请求封装
 */
@Provide()
export class MangoRequestService extends BaseService {
  @Config('module.mango')
  mangoConfig;

  /**
   * post
   */
  post(url, data = {}) {
    const requestConfig = this.mangoConfig.testRequest;
    data['agent_id'] = requestConfig.agent_id;
    data['app_id'] = requestConfig.app_id;
    data['signid'] = this.getApiSign(data, requestConfig.api_token);
    return new Promise((resolve, reject) => {
      var option = {
        url: requestConfig.base_url + url,
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        form: data,
      };
      request(option, function (error, response, body) {
        console.log(body, 'responseresponse');

        if (!error && response.statusCode == 200) {
          if (url == '/api/623a8fc6691fe' || url == '/api/622c5d0a77467') {
            resolve(body);
            return;
          }
          const { code, data } = body;
          if (code === 1) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  /**
   * get
   */
  get(url, params = {}) {
    const requestConfig = this.mangoConfig.testRequest;
    params['agent_id'] = requestConfig.agent_id;
    params['app_id'] = requestConfig.app_id;
    params['signid'] = this.getApiSign(params, requestConfig.api_token);
    return new Promise((resolve, reject) => {
      var option = {
        url: requestConfig.base_url + url,
        method: 'GET',
        timeout: 30000,
        qs: params,
      };
      request(option, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          const { code, data } = body;
          if (code === 1) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  /**
   * getApiSign
   */
  getApiSign(params, token) {
    delete params['signid'];
    const sortedParams = Object.keys(params).sort();
    let str = '';
    for (const key of sortedParams) {
      str += key + params[key];
    }
    const signStr = str + token;
    const apiSign = crypto.createHash('md5').update(signStr).digest('hex');
    return apiSign;
  }
}
